package com.geline.easyexcel.manager;

import cn.hutool.json.JSONUtil;
import com.geline.easyexcel.domain.DynamicSqlBean;
import com.geline.easyexcel.utils.DynamicSqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汇总报表动态SQL管理器
 *
 * @author: mengxin
 * @date: 2024/1/30 15:26
 */
@Slf4j
public class DynamicSqlManager {

    private Map<String, DynamicSqlBean> sqlBeanMap;
    private JdbcTemplate jdbcTemplate;

    public DynamicSqlManager(JdbcTemplate jdbcTemplate){
        this.sqlBeanMap = new HashMap<>();
        this.jdbcTemplate = jdbcTemplate;
    }

    public Map<String, DynamicSqlBean> getSqlBeanMap() {
        return this.sqlBeanMap;
    }

    public JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }

    public void putDynamicSqlBean(String code, DynamicSqlBean bean){
        if(this.sqlBeanMap.containsKey(code)){
            log.warn("find more DynamicSqlBean by code = {}", code);
        }
        this.sqlBeanMap.put(code, bean);
    }

    public List listData(String id, Map<String, Object> example, Class rowClass){
        String runSql = createRunSql(id, example);
        List rowList = jdbcTemplate.query(runSql, new BeanPropertyRowMapper<>(rowClass));
        return rowList;
    }

    public String createRunSql(String code, Map<String, Object> example){
        DynamicSqlBean bean = this.sqlBeanMap.get(code);
        String dynamicSql = bean.getDynamicSql();
        return DynamicSqlUtil.parseSQL(dynamicSql, example);
    }

    public Map<String, String> getVariableMap(String id, Map<String, Object> example){
        DynamicSqlBean reportData = this.sqlBeanMap.get(id);
        Map<String, String> result = new HashMap<>();
        String variableString = reportData.getVariableMap();
        Map<String, String> variableMap = JSONUtil.toBean(variableString, Map.class);
        for(String key : variableMap.keySet()){
            String value = variableMap.get(key);
            for(String code : example.keySet()){
                Object obj = example.get(code);
                if(obj!=null){
                    value = value.replace(String.format("{%s}", code), String.valueOf(obj));
                }
            }
            result.put(key, value);
        }
        return result;
    }

}
